package com.yanx.common.result;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.yanx.common.enums.SystemError;
import lombok.Data;

import java.io.Serializable;

/**
 * 返回统一的数据格式
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements IResult<T>, Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 返回编码
     */
    private Integer code;

    /**
     * 编码描述
     */
    private String msg;

    /**
     * 业务数据
     */
    private T data;

//    //兼容
//    public String getMessage() {
//        return this.getMsg();
//    }

    @Override
    public void init(int code, String msg) {
        this.setCode(code);
        this.setMsg(msg);
    }

    @Override
    public void initData(T data) {
        this.setData(data);
    }

    /**
     * 返回成功结果对象
     *
     * @param <T>
     * @return
     */
    public static <T> Result<T> success() {
        return success(null);
    }

    /**
     * 返回成功结果对象，带data
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> success(T data) {
        Result result = new Result();
        result.init(SUCCESS_CODE, SUCCESS_MSG);
        result.initData(data);
        return result;
    }

    /**
     * 返回失败结果对象
     *
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> Result<T> error(String msg) {
        Result result = new Result();
        result.init(SystemError.E999.toCode(), msg);
        return result;
    }
}
